package com.baidu.leetcode.yangge.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/*
    如何优雅的关闭线程池
 */
public class ThreadPoolUtil {

    /**
     * 如何优雅的关闭线程池
     * 防止线程池关闭之后还有线程未关闭，相当于双端检索机制
     * @param threadPool 线程池
     */
    public static void finalOK_shutdownAndAwaitTermination(ExecutorService threadPool) {
        if (threadPool != null && !threadPool.isShutdown()) {
            threadPool.shutdown();
            try {
                if (!threadPool.awaitTermination(120, TimeUnit.SECONDS)) {
                    threadPool.shutdownNow();
                    if (!threadPool.awaitTermination(120,TimeUnit.SECONDS)) {
                        System.out.println("线程池未被关闭");
                    }
                }
            }catch (InterruptedException e) {
                threadPool.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
}
